package com.hishop.controller.portal;

import com.hishop.common.Constant;
import com.hishop.common.ResponseCode;
import com.hishop.common.ServerResponse;
import com.hishop.pojo.User;
import com.hishop.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by hejie on 2017/7/14.
 */
@Controller
@RequestMapping("/user/springsession")
public class UserSpringSessionController {
    @Autowired
    private IUserService iUserService;

    @RequestMapping(value = "login.do", method = RequestMethod.POST)
    @ResponseBody   //让数据序列化为json格式的数据
    public ServerResponse<User> login(String username, String password, HttpSession session, HttpServletRequest request, HttpServletResponse resp) {
       int a =1/0;

        ServerResponse<User> response = iUserService.login(username, password);
        if (response.isSuccess()) {
            session.setAttribute(Constant.CURRENT_USER, response.getData());
            // CookieUtil.writeLoginToken(resp, session.getId());
            // RedisShardedPoolUtil.setEx(session.getId(), JsonUtil.obj2String(response.getData()), Constant.RedisCacheExtime.REDIS_SESSION_EXTIME);
        }
        return response;
    }

    @RequestMapping(value = "logout.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> logout(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        session.removeAttribute(Constant.CURRENT_USER);
        // String loginToken = CookieUtil.readLoginToken(request);
        // CookieUtil.delLoginToken(request,response);
        // RedisShardedPoolUtil.del(loginToken);
        return ServerResponse.createBySuccess();
    }

    @RequestMapping(value = "get_user_info.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> getUserInfo(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute(Constant.CURRENT_USER);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
       /* String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isBlank(loginToken)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登录，无法获取用户信息");
        }
        String userJson = RedisShardedPoolUtil.get(loginToken);
        User user = JsonUtil.string2Obj(userJson, User.class);*/
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登录，无法获取用户信息");
    }

}
